package cn.com.dstz.web.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import cn.com.dstz.base.action.BaseAction;
import cn.com.dstz.security.encoder.Md5PwdEncoder;
import cn.com.dstz.utils.ActionUtils;
import cn.com.dstz.utils.DataBaseUtils;
import cn.com.dstz.utils.DateUtils;
import cn.com.dstz.utils.FillNameQuery;
import cn.com.dstz.utils.RequestUtils;
import cn.com.dstz.web.constants.Constants;

/**
 * 登录Action
 * @author 叶装装
 * 
 */
public class LoginAct extends BaseAction{
	
	/**
	 * 登录方法
	 */
	public void login( ) {
		
		int validLogin = validLogin( );
		
		Map< String, Object > jsonMap = new HashMap< String, Object >( );
		
		if( validLogin > 0 ){
			jsonMap.put( "status", 0 );
			jsonMap.put( "result", validLogin );
			this.ajaxResponse( JSONObject.fromObject( jsonMap )  );
			return;
		}
		
		Map< String, Object > admin = getAdmin( );
		
		int dbChecking = dbChecking( admin );
		
		//还要验证当前用户是否已被停用 -- > 未实现
		
		if( dbChecking > 0 ){
			jsonMap.put( "status", 0 );
			jsonMap.put( "result", dbChecking );
			this.ajaxResponse( JSONObject.fromObject( jsonMap )  );
			return;
		}
		
		setSessionAttr( Constants.ADMIN_IN_SESSION, admin ); 
		
		int groupId = ( Integer ) admin.get( "groupid" );
		
		// 读取当前用户分组的权限，保存到Session中，然后要以树形显示
		String sql = "select f.* from dstz_function f, dstz_group_function gf where f.id = gf.functionid and gf.groupid =:groupid order by f.displayorder desc,f.parentid asc";
		
		List< Map< String, Object >> purviewList = baseService.queryForListByAll( sql, DataBaseUtils.getData( new String[]{
				"groupid"
		}, new Object[]{
				groupId
		} ) );
		
		setSessionAttr( Constants.ADMIN_PURVIEW, purviewList );
		
		int level = ActionUtils.getAdminLevel( admin );
		
		if( level > 0 ){
			// 获取附加权限
			Map< String, Object > agentConfig = getAgentConfig( groupId );
			if( agentConfig != null && !agentConfig.isEmpty( ) ){
				admin.put( cn.com.dstz.admin.constants.Constants.CONFIG_NAME, true );
				admin.put( cn.com.dstz.admin.constants.Constants.AGENT_CONFIG_IN_SESSION,  agentConfig );
			}else{
				admin.put( cn.com.dstz.admin.constants.Constants.CONFIG_NAME, false );
			}
		}
		
		
		HttpServletRequest request = getRequest( );
		
		addLog( admin, request );
		
		jsonMap.put( "status", 1 );
		jsonMap.put( "url",  request.getContextPath( ) + "/admin/main.jsp" );
		this.ajaxResponse( JSONObject.fromObject( jsonMap )  );
		return;
	}
	
	
	public String loginOut( ) {
		HttpSession session = getSession( );
		session.removeAttribute( Constants.ADMIN_IN_SESSION );
		session.invalidate( );
		return "login" ;
	}
	
	
	private Map< String, Object > getAgentConfig( Integer groupid ){
		String sql = "select * from dstz_agent_config where groupid=:groupid";
		return baseService.queryForMap( sql, FillNameQuery.fillValue( sql, groupid ) );
	}
	
	private Map< String , Object > getAdmin( ){
		
		String sql = "select a.*, g.name as groupname, t.allowlogin,t.ismanager,t.level from dstzadmin a,dstzgroup g, dstz_group_type t where a.groupid=g.id and g.id = t.groupid and username='" + username + "'";
		Map< String, Object > admin = baseService.getData( sql );
		
		return admin;
	}
	
	private void addLog( Map< String, Object > admin, HttpServletRequest request ){
		
		Map< String, Object > insertData = new HashMap< String, Object >( );
		insertData.put( "logindate", DateUtils.getCurrentTime( ) );
		insertData.put( "loginip", RequestUtils.getIpAddr( request ) );
		insertData.put( "loginuser", admin.get( "username" ) );
		insertData.put( "loginuid", admin.get( "id" ) );
		
		baseService.save( "dstz_loginlog", insertData );
		
	}
	
	private int dbChecking( Map< String, Object > admin ){
		if( admin == null || admin.isEmpty( ) ){
			return 1;
		}
		
		String adminPwd = ( String ) admin.get( "password" );
		if( !StringUtils.equals( adminPwd, pwdEncoder.md5( password ) )){
			return 1;
		}
		
		return 0;
		
	}
	
	private int validLogin( ){
		
		if( StringUtils.isBlank( username ) || StringUtils.isBlank( password ) ){
			return 1;
		}
		
		if( StringUtils.isBlank( captcha )){
			return 2;
		}
		
		if( !checkCaptcha ( captcha )){
			return 2;
		}
		
		this.username = decode( username ); // 用户名可能包含中文，现解码 。。 
		
		return 0;
		
	}
	
	private boolean checkCaptcha( String captcha ){
		String captchaFromSession = this.getEntityInSession( Constants.VERIFY_CODE_IN_SESSION );
		return StringUtils.equalsIgnoreCase( captcha, captchaFromSession );
	}
	
	private String username; // 用户名
	private String password;  // 密码
	private String captcha;   // 验证码
	
	
	private Md5PwdEncoder pwdEncoder;

	public Md5PwdEncoder getPwdEncoder( ) {
		return pwdEncoder;
	}

	public void setPwdEncoder( Md5PwdEncoder pwdEncoder ) {
		this.pwdEncoder = pwdEncoder;
	}
	
	
	public String getUsername( ) {
		return username;
	}


	public void setUsername( String username ) {
		if( StringUtils.isNotBlank( username )){
			username = decode( username );
		}
		this.username = username;
	}


	public String getPassword( ) {
		return password;
	}


	public void setPassword( String password ) {
		this.password = password;
	}


	public String getCaptcha( ) {
		return captcha;
	}


	public void setCaptcha( String captcha ) {
		this.captcha = captcha;
	}

	private static final long serialVersionUID = 1L;

}
